<?php
	/*
  
  author: Francis Sem
  	 
  Copyright 2007 francissem@gmail.com 
  Licensed under the Apache License, Version 2.0 (the "License"); 
  you may not use this file except in compliance with the License. 
  You may obtain a copy of the License at http://www.apache.org/licenses/
  LICENSE-2.0 Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  See the License for the specific language governing permissions and
  limitations under the License. 
  
  ---------------------------------------------------------------------------
  
  Example:
  
  $cookieobj = new Cookie("you_name_space");
  
  $cookieobj->you_visited++;
  
  $cookieobj->log[]=date("Y-m-d H:i:s");
  
  $cookieobj->arr["lvl1"]["sublvl1"]="i am here =^^= 1";
  
  $cookieobj->arr["lvl1"]["sublvl2"]="i am here =^^= 2";
  
  $cookieobj->_test="test_private";
  
  $cookieobj->save();
  
  
  var_dump($cookieobj);
  
  */
	

class Cookie{
		
	function Cookie($name=""){
		if(empty($name)){
			$c = $_COOKIE;
		}else{
			$c = $_COOKIE[$name]
		}
		foreach($c as $k=>$v) $this->$k=$v;
		$this->_name = $name;
	}
	
	
	function save($time=0,$path="/",$domain=NULL,$serce=false){
		if($domain==NULL) $domain = $_SERVER["HTTP_HOST"];
	
		$serials=array();

		$this->_recursive("",$this,$this->_name,$serials);
		
		$old_serials = array_map("trim",explode(";",$_SERVER["HTTP_COOKIE"]));
		
		//remove
		foreach(array_diff($old_serials,$serials) as $s){
			$s=explode("=",$s);
			setcookie($s[0],$s[1],1,$path,$domain,$serce);
		}
		
		//add
		foreach(array_diff($serials,$old_serials) as $s){
			$s=explode("=",$s);
			setcookie($s[0],$s[1],$time,$path,$domain,$serce);
		}
		
	}
	
	function clear(){
		foreach($this as $k=>$v) unset($this->$k);
		$this->save(1);
	}
	
	
	function _recursive($name,$input,$path,&$gather){
		$opath=$path;
		foreach($input as $n=>$v){
			if(!preg_match("/^_/",$n)){
				if(is_array($v) || is_object($v)){
					if(empty($name)){
						$path=$n;
					}else{
						$path.="[$n]";
					}
					$this->_recursive($n,$v,$path,$gather);
				}else{
					if(empty($path)){
						$gather[]="$n=$v";
					}else{
						$gather[]="{$path}[$n]=".$v;
					}
				}
				$path=$opath;
			}
		}
	}
	
}

?>